package com.example.zkweixiu.app.activity;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;

import com.example.zkweixiu.app.R;
import com.example.zkweixiu.app.bean.IPBean;
import com.example.zkweixiu.app.myview.DHealthyProgressView;
import com.example.zkweixiu.app.myview.ZzHorizontalProgressBar;
import com.example.zkweixiu.app.pro.PublicPro;
import com.example.zkweixiu.app.service.MyService;
import com.example.zkweixiu.app.utils.SPUtils;
import com.google.gson.Gson;
import com.littlegreens.netty.client.NettyTcpClient;
import com.littlegreens.netty.client.listener.MessageStateListener;
import com.littlegreens.netty.client.listener.NettyClientListener;
import com.vondear.rxtool.RxVibrateTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.RxTextViewVertical;
import com.vondear.rxui.view.dialog.RxDialogShapeLoading;
import com.yanzhenjie.sofia.Sofia;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class Unit3Activity extends AppCompatActivity implements View.OnClickListener {

    private DHealthyProgressView healthyProgressView;
    private RxTextViewVertical rx_text_view;
    private Chronometer my_chains;
    private TextView tv_title;
    private ImageButton img_backgroud;
    private ImageButton bt_jianqu;
    private Context context;
    private int progress;
    private ArrayList<String> titleList = new ArrayList<String>();
    private ZzHorizontalProgressBar pro_bar;
    private String user_t;
    private String ip;
    private String uuid;
    private String status;
    private String unit_name;
    private String zdmd;
    private int my_wd;
    private Button btn_log_to; //启动关闭按钮

    // private int pro_beifen; //调温之前记录当前进度

    private boolean stop_of = true;

    private NettyTcpClient mNettyTcpClient;
    private int fewClic = 1; //是否为点击事件
    private int setClic = 1; //是否为增加温度点击事件
    private boolean xinc = true; //是否结束减少线程
    private boolean dasc = true; //是否结束增加线程
    private boolean axjc = false; //是否接收机器的设定温度
    private View view_littles3;
    private View view_littles2;
    private View view_littles1;
    private ImageView iv_mzd3;
    private ImageView iv_mzd2;
    private ImageView iv_mzd1;
    private TextView tv_tc;
    private RxDialogShapeLoading rxDialogShapeLoading;

    private boolean is_stop = true;
    private int is_stop2 = 0;
/*    private boolean onwt = true;
    private boolean ifwt = true;*/
    //设置变量 默认为 true
    //触发点击或者长按事件  如果是true 进入 记录变量值  并置为  false
    //发送事件 重置为true

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 450:
                    // Toast.makeText(getApplicationContext(), "连接成功", Toast.LENGTH_SHORT).show();
                    break;
                case 200:
                    my_chains2.stop(); //停止计时


                    if (is_stop) {
                        btn_log_to.setEnabled(true); //点击事件释放
                        refreshNf();
                    }


                    // rx_text_view.setTextList(titleList);
                    //rx_text_view.notify();

                    if (rxDialogShapeLoading != null) {
                        rxDialogShapeLoading.dismiss();
                    }


                //    pro_bar.setProgress(progress);
                    //RxToast.normal(getApplicationContext(), "修改成功").show();
                    break;

                case 500:
                    my_chains2.stop(); //停止计时
                    btn_log_to.setEnabled(true); //点击事件释放
                    stop_of = true; //释放锁 使页面跟随实时数据变化

                    refreshNf();

                    //rx_text_view.notify();

                    if (rxDialogShapeLoading != null) {
                        rxDialogShapeLoading.dismiss();
                    }

                    pro_bar.setProgress(progress); //设置进度条的刻度
                    //设置刻度条的进度


                    if (rxDialogShapeLoading != null) {
                        rxDialogShapeLoading.dismiss();
                    }


                    //RxToast.normal(getApplicationContext(), "修改失败").show();

                    break;


                case 4002:

/*                    if (she == 2) {
                        pro_bar.setProgress(pro_beifen); //设置进度条的刻度
                        healthyProgressView.setmValue(pro_beifen); //设置刻度条的进度
                    }*/
                    my_chains2.stop(); //停止计时

                    btn_log_to.setEnabled(true); //点击事件释放


                    if (rxDialogShapeLoading != null) {
                        rxDialogShapeLoading.dismiss();
                    }
                    titleList.clear();
                    titleList.add("设备离线");
                    unitStop();
                    RxToast.normal(getApplicationContext(), "设备离线,正在重新连接").show();
                    getNewIp();
                    break;

                case 666:
                    // RxToast.success(getApplicationContext(), "连接成功!", Toast.LENGTH_SHORT, true).show();
                    break;


                case 690:
                    pro_bar.setProgress(progress);
                    break;


                case 501:

                    refreshNf();

                    //rx_text_view.notify();
/*
                    if (rxDialogShapeLoading != null) {
                        rxDialogShapeLoading.dismiss();
                    }*/


                    //shediwd;
                    int i = Integer.parseInt(shediwd) - 10;
                    progress = i;
                    pro_bar.setProgress(i); //设置进度条的刻度
                    //healthyProgressView.setmValue(i); //设置刻度条的进度


                    if (rxDialogShapeLoading != null) {
                        rxDialogShapeLoading.dismiss();
                    }


                    // RxToast.normal(getApplicationContext(), "修改失败").show();
                    break;


                case 982:

                    is_stop2 = 0;
                    int ui = Integer.parseInt(this_wd) - 10;

                    progress = ui;
                    pro_bar.setProgress(ui); //设置进度条的刻度
                    //healthyProgressView.setmValue(i); //设置刻度条的进度


                    if (rxDialogShapeLoading != null) {
                        rxDialogShapeLoading.dismiss();
                    }
                    break;

/*                case 456:
                    int ui2 = Integer.parseInt(shediwd) - 10;

                    progress = ui2;
                    pro_bar.setProgress(ui2); //设置进度条的刻度
                    break;*/


                case 369:
                    Toast.makeText(context, "已经是最高温度啦~", Toast.LENGTH_SHORT).show();

                    break;


                case 368:
                    Toast.makeText(context, "已经是最低温度啦~", Toast.LENGTH_SHORT).show();

                    break;


            }
        }
    };
    private String mydatas = "-1";
    private String datas;
    private String gongshui;
    private String shishi_stop;
    private String this_wd;

    /**
     * 页面状态刷新
     */
    private void refreshNf() {

        if ("0".equals(status)) {
            //  titleList.clear();
            // titleList.add("设备已关闭");
            //     titleList.add("设备正常运行");
            unitStop();

        } else if ("2".equals(status)) {
            //    titleList.clear();
            //   titleList.add("设备已开启");
            //titleList.add("设备正在执行命令...");
            btn_log_to.setText("点击关闭");
            unitStart();
        } else {


            //    titleList.clear();
            // titleList.add("设备已开启");
            //   titleList.add("设备正常运行");
            btn_log_to.setText("点击关闭");
            unitStart();
        }

        if ("1".equals(unit_stop)) {
            //  titleList.clear();
            //  titleList.add("设备正在关闭 请稍后");

            btn_log_to.setText("关机中,请稍后...");
            //  unitStart();


        } else if ("2".equals(unit_stop)) {
            //titleList.clear();
            //  titleList.add("正在转换冷热模式 请稍后");
            btn_log_to.setText("正在转换冷热模式,请稍后..");
            //unitStart();
        }

        setCole();
/*        rx_text_view.setTextList(titleList);
        rx_text_view.setText(12, 5, 0xff766156);//设置属性*/
    }

    private String unit_stop;
    private int she;
    private Chronometer my_chains2;
    private Chronometer my_chains3;
    private String shediwd;
    private TextView tv_hui_shui;

    public  boolean isServiceRunning(Context context, String serviceName) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceInfoList = manager.getRunningServices(200);
        if (serviceInfoList.size() <= 0) {
            return false;
        }
        for (ActivityManager.RunningServiceInfo info : serviceInfoList) {
            if (info.service.getClassName().equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unit3);

        if (!isServiceRunning(this,"com.example.zkweixiu.app.service.MyService")){
            Log.e("MyService","死去了");
            startService(new Intent(this, MyService.class));
        }else {
            Log.e("MyService","活着");
        }
        initView();


    }

    private void initView() {
        Sofia.with(Unit3Activity.this).statusBarDarkFont().statusBarBackground(Color.parseColor("#F5F6F9"));

        context = Unit3Activity.this;
        Intent intent = getIntent();
    //    user_t = intent.getStringExtra("user_t");
        ip = intent.getStringExtra("ip");
        uuid = intent.getStringExtra("uuid");
        user_t = intent.getStringExtra("user_t");
        status = intent.getStringExtra("status");
        unit_name = intent.getStringExtra("unit_name");//设备别名

     //   gongshui = intent.getStringExtra("gongshui"); //用户供水温度
        zdmd = (String) SPUtils.get(getApplicationContext(), "zdmd", "-1");
        healthyProgressView = findViewById(R.id.simple);

        healthyProgressView.beginContinue(false);

        healthyProgressView.setInterpolator(new AccelerateInterpolator());


        sendService();//连接TCP服务器
        rx_text_view = findViewById(R.id.rx_text_view); //轮训的text
        View view_remove = findViewById(R.id.view_remove); //退出
        ImageView im_img = findViewById(R.id.im_img); //退出
        ImageView iv_kefu = findViewById(R.id.iv_kefu); //跳转
        view_remove.setOnClickListener(this); //注册监听事件
        im_img.setOnClickListener(this); //注册监听事件
        iv_kefu.setOnClickListener(this); //注册监听事件


        my_chains = findViewById(R.id.my_chains);        //计时
        my_chains2 = findViewById(R.id.my_chains2);        //计时2
        my_chains3 = findViewById(R.id.my_chains3);        //计时3

        tv_title = findViewById(R.id.tv_title);        //标题
        img_backgroud = findViewById(R.id.img_backgroud); //温度增加
        bt_jianqu = findViewById(R.id.bt_jianqu); //温度减少
        pro_bar = findViewById(R.id.pro_bar); //进度条
        btn_log_to = findViewById(R.id.btn_log_to);        //启动按钮
        tv_tc = findViewById(R.id.tv_tc); //温度文字

        view_littles3 = findViewById(R.id.view_littles3); //小不点
        view_littles2 = findViewById(R.id.view_littles2);
        view_littles1 = findViewById(R.id.view_littles1);
        tv_hui_shui = findViewById(R.id.tv_hui_shui); //供水温度 (显示回水字段)

        //模式图片
        iv_mzd3 = findViewById(R.id.iv_mzd3); //制热
        iv_mzd2 = findViewById(R.id.iv_mzd2); //节能
        iv_mzd1 = findViewById(R.id.iv_mzd1); //制冷

        healthyProgressView.setRotation(-141f); //旋转刻度条
        my_chains.setAlpha(0.0f); //计时器不可见
        my_chains2.setAlpha(0.0f); //计时器不可见
        my_chains3.setAlpha(0.0f); //计时器不可见
        int user_wd = Integer.parseInt(user_t); //转换传入的温度
        progress = user_wd - 10; //计算进度条的刻度值
        pro_bar.setProgress(progress); //设置进度条的刻度
        //设置刻度条的进度
        healthyProgressView.setmValue(progress);
        Log.e("bt_jianqu", "进来" + progress);
        tv_title.setText(unit_name);
        //pro_bar.setGradientColorAndBorderColor(Color.parseColor("#AFB4C2"), Color.parseColor("#AFB4C2"), Color.parseColor("#D3D7E5"));

        tv_tc.setText(String.valueOf(user_wd));
      //  tv_hui_shui.setText("  供水 " + gongshui);

        if ("0".equals(status)) {
            titleList.add("设备已关闭");
            unitStop();

        } else {
            titleList.add("设备已开启");

            unitStart(); //设备启动


        }


        if (user_wd >= 10 & user_wd <= 19) {

            view_littles3.setVisibility(View.INVISIBLE);
            view_littles2.setVisibility(View.INVISIBLE);
            view_littles1.setVisibility(View.VISIBLE);
            Glide.with(getApplicationContext()).load(R.drawable.zhileng_jergg1).into(iv_mzd1);
            Glide.with(getApplicationContext()).load(R.drawable.jieneng_jer1).into(iv_mzd2);
            Glide.with(getApplicationContext()).load(R.drawable.zhire_jer1).into(iv_mzd3);
            //tv_date1.setText("制冷模式");
        } else if (user_wd >= 20 & user_wd <= 25) {

            view_littles3.setVisibility(View.INVISIBLE);
            view_littles2.setVisibility(View.VISIBLE);
            view_littles1.setVisibility(View.INVISIBLE);
            Glide.with(getApplicationContext()).load(R.drawable.zhileng_gegy1).into(iv_mzd1);
            Glide.with(getApplicationContext()).load(R.drawable.jieneng_jergg1).into(iv_mzd2);
            Glide.with(getApplicationContext()).load(R.drawable.zhire_jer1).into(iv_mzd3);
/*            Glide.with(getApplicationContext()).load(R.mipmap.unit_jien).into(iv_img_ms);
            tv_date1.setText("节能模式");*/
        } else {
            view_littles3.setVisibility(View.VISIBLE);
            view_littles2.setVisibility(View.INVISIBLE);
            view_littles1.setVisibility(View.INVISIBLE);
            Glide.with(getApplicationContext()).load(R.drawable.zhileng_gegy1).into(iv_mzd1);
            Glide.with(getApplicationContext()).load(R.drawable.jieneng_jer1).into(iv_mzd2);
            Glide.with(getApplicationContext()).load(R.drawable.zhire_jergg1).into(iv_mzd3);
/*            Glide.with(getApplicationContext()).load(R.mipmap.unit_zhire).into(iv_img_ms);
            tv_date1.setText("制热模式");*/
        }


        rx_text_view.setTextList(titleList);
        rx_text_view.setText(12, 5, 0xff766156);//设置属性
        rx_text_view.setTextStillTime(2000);//设置停留时长间隔
        rx_text_view.setAnimTime(130);//设置进入和退出的时间间隔


        monitor(); //各种事件的监听

        setCole();

    }

    /***
     * 设备启动
     * */
    private void unitStart() {
        healthyProgressView.setProgressColor(Color.parseColor("#2E7BE7"));
        healthyProgressView.inva();
        btn_log_to.setBackground(getResources().getDrawable(R.drawable.bg_btn_login_selected7));
        view_littles3.setBackground(getResources().getDrawable(R.drawable.oval_bg2));
        view_littles2.setBackground(getResources().getDrawable(R.drawable.oval_bg2));
        view_littles1.setBackground(getResources().getDrawable(R.drawable.oval_bg2));
        //healthyProgressView.
        setCole();
    }

    /**
     * 设备关闭
     */
    private void unitStop() {
        healthyProgressView.setProgressColor(Color.parseColor("#4C5364"));
        healthyProgressView.inva();
        //  healthyProgressView.setProgressColor(Color.parseColor("#2E7BE7"));
        btn_log_to.setBackground(getResources().getDrawable(R.drawable.bg_btn_login_selected6));
        view_littles3.setBackground(getResources().getDrawable(R.drawable.oval_bg3));
        view_littles2.setBackground(getResources().getDrawable(R.drawable.oval_bg3));
        view_littles1.setBackground(getResources().getDrawable(R.drawable.oval_bg3));
        btn_log_to.setText("点击启动");
        setCole();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void monitor() {
        pro_bar.setOnProgressChangedListener(new ZzHorizontalProgressBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(ZzHorizontalProgressBar progressBar, int max, int progress) {

                if ("-1".equals(zdmd)) {
                    RxVibrateTool.vibrateOnce(getApplicationContext(), 130);
                }
                my_wd = progress + 10; //当前设备设定温度
                tv_tc.setText(String.valueOf(my_wd)); //文字显示的温度
                setCole();

                Log.e("sendUnitKG", progress + "");
/*                healthyProgressView.setmValue(progress);
                healthyProgressView.setmValue(progress);
                healthyProgressView.setmValue(progress);
                healthyProgressView.setmValue(progress);
                healthyProgressView.setmValue(progress);
                healthyProgressView.setmValue(progress);
                healthyProgressView.setmValue(progress);*/
                if (my_wd >= 10 & my_wd <= 19) {

                    view_littles3.setVisibility(View.INVISIBLE);
                    view_littles2.setVisibility(View.INVISIBLE);
                    view_littles1.setVisibility(View.VISIBLE);
                    Glide.with(getApplicationContext()).load(R.drawable.zhileng_jergg1).into(iv_mzd1);
                    Glide.with(getApplicationContext()).load(R.drawable.jieneng_jer1).into(iv_mzd2);
                    Glide.with(getApplicationContext()).load(R.drawable.zhire_jer1).into(iv_mzd3);
                    //tv_date1.setText("制冷模式");
                } else if (my_wd >= 20 & my_wd <= 25) {

                    view_littles3.setVisibility(View.INVISIBLE);
                    view_littles2.setVisibility(View.VISIBLE);
                    view_littles1.setVisibility(View.INVISIBLE);
                    Glide.with(getApplicationContext()).load(R.drawable.zhileng_gegy1).into(iv_mzd1);
                    Glide.with(getApplicationContext()).load(R.drawable.jieneng_jergg1).into(iv_mzd2);
                    Glide.with(getApplicationContext()).load(R.drawable.zhire_jer1).into(iv_mzd3);
/*            Glide.with(getApplicationContext()).load(R.mipmap.unit_jien).into(iv_img_ms);
            tv_date1.setText("节能模式");*/
                } else {
                    view_littles3.setVisibility(View.VISIBLE);
                    view_littles2.setVisibility(View.INVISIBLE);
                    view_littles1.setVisibility(View.INVISIBLE);
                    Glide.with(getApplicationContext()).load(R.drawable.zhileng_gegy1).into(iv_mzd1);
                    Glide.with(getApplicationContext()).load(R.drawable.jieneng_jer1).into(iv_mzd2);
                    Glide.with(getApplicationContext()).load(R.drawable.zhire_jergg1).into(iv_mzd3);
/*            Glide.with(getApplicationContext()).load(R.mipmap.unit_zhire).into(iv_img_ms);
            tv_date1.setText("制热模式");*/
                }
                //   Log.e("onSecondProgressChanged", progress + "hah");

                if (progress >= 35) {
                    healthyProgressView.setmValue(35);
                } else if (progress <= 0) {
                    healthyProgressView.setmValue(1);
                } else {
                    healthyProgressView.setmValue(progress);
                }


                healthyProgressView.inva();
            }

            @Override
            public void onSecondProgressChanged(ZzHorizontalProgressBar progressBar, int max, int progress) {
                //Log.e("onSecondProgressChanged", progress + "");
            }
        });


        //======================降温监听============================================
        bt_jianqu.setOnClickListener(new View.OnClickListener() { //点击
            @Override
            public void onClick(View view) {
 /*               if (onwt) {
                    pro_beifen = progress;
                    onwt = false;

                }*/
                //  is_stop = true;

                boolean endB = isEndB();

                if (!endB) {
                    return;
                }
                is_stop = true;

                progress--;

                if (progress <= 0) {
                    Toast.makeText(context, "已经是最低温度啦~", Toast.LENGTH_SHORT).show();
                    progress = 0;
                }
                Log.e("bt_jianqu", "点击" + progress);

                pro_bar.setProgress(progress);
                //设置刻度条的进度
                my_chains.setBase(SystemClock.elapsedRealtime()); //每次点击重置计时器

                my_chains.start();//开始计时
                fewClic = 1;

/*                timer.
                timer.start();*/
            }
        });

        bt_jianqu.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    //  Log.e("bt_jianqu", "松开");


                    boolean endB = isEndB();

                    if (!endB) {
                        return endB;
                    }
                    xinc = false;
                    if (fewClic != 1) {
                        my_chains.setBase(SystemClock.elapsedRealtime()); //重置计时器  //发送调温命令

                        my_chains.start();//开始计时
                        fewClic = 1;
                        //设置刻度条的进度

                    }
                }


                return false;
            }
        });

        bt_jianqu.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                // Log.e("bt_jianqu", "长按");
/*                if (onwt) {
                    pro_beifen = progress;
                    onwt = false;

                }*/

                boolean endB = isEndB();

                if (!endB) {
                    return !endB;
                }

                is_stop = true;

                fewClic = 2;
                xinc = true;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (xinc) {

                            progress--;
                            if (progress <= 0) {
                                mHandler.sendEmptyMessage(368);
                                progress = 0;
                            }


                            mHandler.sendEmptyMessage(690);
                            // //设置刻度条的进度
                            SystemClock.sleep(300);
                        }
                    }
                }).start();
                return true;
            }
        });


        //======================增加温度监听=====================================

        img_backgroud.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
/*                if (ifwt) {
                    pro_beifen = progress;
                    ifwt = false;
                }*/
                boolean endB = isEndB();

                if (!endB) {
                    return ;
                }

                is_stop = true;
                progress++;
                if (progress >= 35) {
                    Toast.makeText(context, "已经是最高温度啦~", Toast.LENGTH_SHORT).show();
                    progress = 35;
                }

                pro_bar.setProgress(progress);
                //设置刻度条的进度

                my_chains.setBase(SystemClock.elapsedRealtime()); //每次点击重置计时器

                my_chains.start();//开始计时
                setClic = 1;
            }
        });


        img_backgroud.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
/*                private int fewClic = 1; //是否为点击事件
                private int setClic = 1; //是否为增加温度点击事件
                private boolean xinc = true; //是否结束减少线程
                private boolean dasc = true; //是否结束增加线程*/
                //      Log.e("bt_jianqu", "长按");
 /*               if (ifwt) {
                    pro_beifen = progress;
                    ifwt = false;
                }*/

                boolean endB = isEndB();

                if (!endB) {
                    return !endB;
                }
                is_stop = true;

                setClic = 2;
                dasc = true;

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (dasc) {

                            progress++;
                            if (progress >= 35) {
                                mHandler.sendEmptyMessage(369);
                                progress = 35;
                            }

                            //  pro_bar.setProgress(progress);
                            mHandler.sendEmptyMessage(690);
                            // //设置刻度条的进度
                            SystemClock.sleep(300);
                        }
                    }
                }).start();
                return true;

            }
        });


        img_backgroud.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    // is_stop = true;
                    //  Log.e("bt_jianqu", "松开");
                    /*                private int fewClic = 1; //是否为点击事件
                private int setClic = 1; //是否为增加温度点击事件
                private boolean xinc = true; //是否结束减少线程
                private boolean dasc = true; //是否结束增加线程*/

                    boolean endB = isEndB();

                    if (!endB) {
                        return endB;
                    }
                    dasc = false; //结束子线程
                    if (setClic != 1) {
                        my_chains.setBase(SystemClock.elapsedRealtime()); //重置计时器  //发送调温命令

                        my_chains.start();//开始计时
                        setClic = 1; //重置为点事件
                        //设置刻度条的进度

                    }
                }


                return false;
            }
        });

        //============================发送调温监听===================================================


        my_chains.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {

            @Override
            public void onChronometerTick(Chronometer chronometer) {
                //SystemClock.elapsedRealtime()系统当前时间
                //chronometer.getBase()记录计时器开始时的时间
                if ((SystemClock.elapsedRealtime() - chronometer.getBase()) > 1000) {
                    my_chains.stop(); //停止计时

                    rxDialogShapeLoading = new RxDialogShapeLoading(context);

                    rxDialogShapeLoading.show();
                    //   Log.e("bt_jianqu", "发送调温");
                    //my_chains.setBase(SystemClock.elapsedRealtime());
                    she = 2;
/*
                    if (!ifwt) {
                        ifwt = true;
                    }
                    if (!onwt) {
                        onwt = true;
                    }
*/

                    sendMsg(my_wd, "03");


                }
            }
        });


        my_chains2.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() { //发送命令的计时

            @Override
            public void onChronometerTick(Chronometer chronometer) {
                //SystemClock.elapsedRealtime()系统当前时间
                //chronometer.getBase()记录计时器开始时的时间
                if ((SystemClock.elapsedRealtime() - chronometer.getBase()) > 9000) {
                    stop_of = true; //释放锁 使页面跟随实时数据变化

              /*      if (!stop_of) {
                    }*/
                    my_chains2.stop(); //停止计时
                    mHandler.sendEmptyMessage(501);
                    btn_log_to.setEnabled(true); //点击事件释放
                }
            }
        });

        my_chains3.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() { //发送命令的计时

            @Override
            public void onChronometerTick(Chronometer chronometer) {
                //SystemClock.elapsedRealtime()系统当前时间
                //chronometer.getBase()记录计时器开始时的时间
                if ((SystemClock.elapsedRealtime() - chronometer.getBase()) > 9000) { //开机未操作6秒后释放锁
                    stop_of = true; //释放锁 使页面跟随实时数据变化
             /*       if (!stop_of) {

                    }*/
                    my_chains3.stop(); //停止计时

                    if (is_stop) { //开机事件
                        btn_log_to.setEnabled(true); //点击事件释放
                    }
                }
            }
        });


        //=========================================开关机
        btn_log_to.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                she = 1;
                rxDialogShapeLoading = new RxDialogShapeLoading(context);

                rxDialogShapeLoading.show();

                if ("100".equals(status)) {
                    if (rxDialogShapeLoading != null) {
                        rxDialogShapeLoading.dismiss();
                    }
                    Toast.makeText(context, "设备已离线", Toast.LENGTH_SHORT).show();
                    return;
                }

                if ("6".equals(status)) {
                    if (rxDialogShapeLoading != null) {
                        rxDialogShapeLoading.dismiss();
                    }
                    Toast.makeText(context, "设备处于防冻模式!", Toast.LENGTH_SHORT).show();
                    return;
                }


                if ("1".equals(unit_stop)) {
                    if (rxDialogShapeLoading != null) {
                        rxDialogShapeLoading.dismiss();
                    }
                    Toast.makeText(context, "设备正在关闭 请稍后...", Toast.LENGTH_SHORT).show();
                    return;
                }


                if ("2".equals(unit_stop)) {
                    if (rxDialogShapeLoading != null) {
                        rxDialogShapeLoading.dismiss();
                    }
                    Toast.makeText(context, "压缩机正在转换模式 请稍后...", Toast.LENGTH_SHORT).show();
                    return;
                }

                if ("0".equals(status)) {
                    sendUnitKG("01,"); //开机
                    stop_of = false;  //锁定实时数据获取
                    is_stop = true; //开机

                } else {
                    sendUnitKG("02,");
                    stop_of = false; //锁定实时数据获取
                    is_stop = false; //关机
                }


                btn_log_to.setEnabled(false); //点击事件禁止
            }
        });
    }

    private boolean isEndB() {
        if ("100".equals(status)) {
            if (rxDialogShapeLoading != null) {
                rxDialogShapeLoading.dismiss();
            }
            Toast.makeText(context, "设备已离线", Toast.LENGTH_SHORT).show();
            return false;
        }

        if ("6".equals(status)) {
            if (rxDialogShapeLoading != null) {
                rxDialogShapeLoading.dismiss();
            }
            Toast.makeText(context, "设备处于防冻模式!", Toast.LENGTH_SHORT).show();
            return false;
        }


        if ("1".equals(unit_stop)) {
            if (rxDialogShapeLoading != null) {
                rxDialogShapeLoading.dismiss();
            }
            Toast.makeText(context, "设备正在关闭 请稍后...", Toast.LENGTH_SHORT).show();
            return false;
        }


        if ("2".equals(unit_stop)) {
            if (rxDialogShapeLoading != null) {
                rxDialogShapeLoading.dismiss();
            }
            Toast.makeText(context, "压缩机正在转换模式 请稍后...", Toast.LENGTH_SHORT).show();
            return false;
        }


        return true;
    }


    @Override
    protected void onResume() {
        super.onResume();
/*        if (mNettyTcpClient.getConnectStatus()) {

        } else { //没有连接 连接
            mNettyTcpClient.connect();

        }*/
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        rx_text_view.startAutoScroll();

    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
        rx_text_view.stopAutoScroll();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mNettyTcpClient.disconnect();
        PublicPro.ISSERVICE = false;

        stopService(new Intent(this, MyService.class));
    }

    private void sendService() {

        mNettyTcpClient = new NettyTcpClient.Builder()
                .setHost(PublicPro.SERVICE_TCP)    //设置服务端地址
                .setTcpPort(9002) //设置服务端端口号
                .setMaxReconnectTimes(5)    //设置最大重连次数
                .setReconnectIntervalTime(5)    //设置重连间隔时间。单位：秒
                .setSendheartBeat(true) //设置发送心跳
                .setHeartBeatInterval(19)    //设置心跳间隔时间。单位：秒
                // .setHeartBeatData(new byte[]{0x03, 0x0F, (byte) 0xFE, 0x05, 0x04, 0x0a}) //设置心跳数据，可以是String类型，也可以是byte[]
                .setHeartBeatData("00&_") //设置心跳数据，可以是String类型，也可以是byte[]，以后设置的为准
                .setIndex(10089)    //设置客户端标识.(因为可能存在多个tcp连接)

                .build();


        mNettyTcpClient.setListener(new NettyClientListener() {
            @Override
            public void onMessageResponseClient(Object msg, int index) {
                String ponse = msg.toString();
                Log.e("sendUnitKG", ponse);

                if (ponse.contains("A1")) {
                    mHandler.sendEmptyMessage(450);
                    // getActivity().startService(new Intent(getActivity(), MyService.class));
                } else if (ponse.contains(",200")) {
                    //Log.e("test", "出错了");
                    // NEW_CON,/111.61.64.62:62927,31,0,0,200

                    String[] split = ponse.split(",");

                    status = split[3];
                    user_t = split[2];
                    unit_stop = split[4];//系统停机状态值

                    shishi_stop = split[4];//系统停机状态值
                    progress = Integer.parseInt(user_t) - 10;


                    mHandler.sendEmptyMessage(200);

                    Log.e("sendUnitKG", "执行");
                } else if (ponse.contains(",400")) { //控制失败
                    String[] split = ponse.split(",");

                    status = split[3];
                    user_t = split[2];
                    unit_stop = split[4];//系统停机状态值
                    shishi_stop = split[4];//系统停机状态值
                    progress = Integer.parseInt(user_t) - 10;

                    mHandler.sendEmptyMessage(500);


                } else if (ponse.contains("4002,")) {


                    status = "100";
                    mHandler.sendEmptyMessage(4002);
                    // getNewIp(); 重新连接
                }

                // btn_log_to.setEnabled(true); //点击事件释放
            }

            @Override
            public void onClientStatusConnectChanged(int statusCode, int index) {
                //  Log.e("setListener", String.valueOf(statusCode));
            }
        });

        mNettyTcpClient.connect();
    }


    /**
     * 发送控制消息
     */
    private void sendMsg(int progress, String s) {
        try {
            Log.e("sendUnitKG", "执行调温" + progress);
            mNettyTcpClient.sendMsgToServer(("APP_CON," + s + "," + progress + "," + ip + "&_").getBytes("UTF-8"), new MessageStateListener() {
                @Override
                public void isSendSuccss(boolean isSuccess) {

                    if (isSuccess) {



                    }
/*                    if (isSuccess) {
                        // Log.d("isSuccess", "send successful");
                    } else {
                        Log.d("isSuccess", "设备离线");
                    }*/
                }
            });

            my_chains2.setBase(SystemClock.elapsedRealtime()); //重置计时器  //发送调温命令
            my_chains2.start();//开始计时

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Toast.makeText(this, "出错了~", Toast.LENGTH_SHORT).show();
        }
    }


    private int count = 0;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Object event) {
        //返回的实时数据
        datas = PublicPro.ac_time.get(uuid);
        //   Log.e("sendUnitKG", datas);

        if (datas != null) {
/*            if (mydatas.equals(datas)) {
                return;
            }
            mydatas = datas;*/

            //  Log.e("sendUnitKG", "到此处");
            String[] split = datas.split(",");


            //系统设定温度
            shediwd = split[2];
            //     供水 18.6
            tv_hui_shui.setText("  供水 " + split[6]);

/*            if ("0".equals(status)) {
                tv_sta_data1.setText("已关闭");
            } else {
                tv_sta_data1.setText("已开启");
            }*/


            if (!is_stop) { //关机事件
                if ("0".equals(split[3]) & "0".equals(split[4])) {
                    status = split[3];// 系统状态值0-6(状态值)
                    unit_stop = split[4];//系统停机状态值
                    btn_log_to.setEnabled(true); //点击事件释放
                    refreshNf();
                }
            }


            if ("2".equals(shishi_stop)){
                is_stop2 = 1;
                unit_stop = "2";
                count++;
                if (count >= 9){
                    count = 0;
                    shishi_stop = "0";
                    is_stop2 = 2;
                }


            }else {
                unit_stop = split[4];//系统停机状态值

            }

            if (stop_of) { //正常
                status = split[3];// 系统状态值0-6(状态值)

            //    zdmd = "2";
                if (is_stop2 == 2){
                    if ("0".equals(split[4])) {
                        this_wd = split[2];
                        mHandler.sendEmptyMessage(982);
                        refreshNf();
                        axjc = false;
                        return;
                    }
                }

                if ("2".equals(unit_stop)){
                    axjc = true;
                }

                if (axjc){

                    if ("0".equals(unit_stop)){
                        axjc = false;
                        this_wd = split[2];
                        mHandler.sendEmptyMessage(982);
                        refreshNf();
                        return;
                    }

                }


                refreshNf();
          //      mHandler.sendEmptyMessage(456);
               // pro_bar.setProgress();
                Log.e("sendUnitKG", split[4]);
                Log.e("sendUnitKG", shediwd);
            }



            //rx_text_view.notify();
        }

    }

    public void getNewIp() { //设备离线重连
        OkHttpUtils
                .get()
                .url(PublicPro.GET_UNIT_IP)
                .addParams("uuid", uuid)
                .build()
                .execute(new StringCallback() {


                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.e("HomeFragment1", e.getMessage());
                        mHandler.sendEmptyMessage(4003);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("HomeFragment1", response);

                        IPBean ipBean = new Gson().fromJson(response, IPBean.class);

                        if (ipBean.getStatus() == 200) {
                            if (!ipBean.getData().get(1).equals("100")) {
                                String ips = ipBean.getData().get(0);

                                PublicPro.IP_UUID.put(uuid, ips);
                                ip = ips;
                                mHandler.sendEmptyMessage(666);

                            } else {
                                mHandler.sendEmptyMessage(4003);
                            }
                        }

                    }
                });
    }

    /**
     * 开关机
     */
    private void sendUnitKG(String status) {
        try {
            Log.e("sendUnitKG", "执行" + status);
            String concat = "APP_CON,".concat(status).concat("15,").concat(ip).concat("&_");
            Log.e("sendUnitKG", concat);
            mNettyTcpClient.sendMsgToServer(concat.getBytes(), new MessageStateListener() {
                @Override
                public void isSendSuccss(boolean isSuccess) {
                    if (isSuccess) {

                    }
/*                    if (isSuccess) {
                        // Log.d("isSuccess", "send successful");
                    } else {
                        Log.d("isSuccess", "设备离线");
                    }*/
                }
            });

            if ("02,".equals(status)) {
                // titleList.clear();
                //titleList.add("设备正在关闭 请稍后...");
                //   rx_text_view.setTextList(titleList);
                //rx_text_view.setText(12, 5, 0xff766156);//设置属性
                btn_log_to.setText("关机中,请稍后..");
            }


            my_chains3.setBase(SystemClock.elapsedRealtime()); //重置计时器  //发送开机命令结束
            my_chains3.start(); //开始计时

            my_chains2.setBase(SystemClock.elapsedRealtime()); //重置计时器  //发送调温命令

            my_chains2.start();//开始计时


        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "出错了~", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View view) {

/*        view_remove.setOnClickListener(this); //注册监听事件
        im_img.setOnClickListener(this); //注册监听事件
        iv_kefu.setOnClickListener(this); //注册监听事件*/
        switch (view.getId()) {
            case R.id.view_remove:
            case R.id.im_img:
                finish();
                break;

            case R.id.iv_kefu:
  /*              Intent intent = new Intent(context, MyDataActivity.class);
                intent.putExtra("uuid", uuid);
                intent.putExtra("ip", ip);
                intent.putExtra("unit_name", unit_name);

                startActivity(intent);*/
                break;

        }
    }


    private void setCole(){
        //#898989 主色
//#DBDBDB //关机辅色
        if ("0".equals(status)) {
            pro_bar.setGradientColorAndBorderColor(Color.parseColor("#DBDBDB"), Color.parseColor("#898989"), Color.parseColor("#FFFFFF"));
        } else {

            switch (progress) {
                case 45:
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#ff5d3d"), Color.parseColor("#ff3d5d"), Color.parseColor("#FFFFFF"));
                    break;
                case 44:
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#ff6a3d"), Color.parseColor("#ff3d51"), Color.parseColor("#FFFFFF"));
                    break;
                case 43:
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#ff773d"), Color.parseColor("#ff3d3d"), Color.parseColor("#FFFFFF"));
                    break;
                case 42:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#ff843d"), Color.parseColor("#ff4a3d"), Color.parseColor("#FFFFFF"));
                    break;

                case 41:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#ff913d"), Color.parseColor("#ff573d"), Color.parseColor("#FFFFFF"));
                    break;

                case 40:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#ff9e3d"), Color.parseColor("#ff643d"), Color.parseColor("#FFFFFF"));
                    break;


                case 39:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#ffab3d"), Color.parseColor("#ff713d"), Color.parseColor("#FFFFFF"));
                    break;

                case 38:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#ffb83d"), Color.parseColor("#ff7e3d"), Color.parseColor("#FFFFFF"));
                    break;


                case 37:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#ffc53d"), Color.parseColor("#ff8b3d"), Color.parseColor("#FFFFFF"));
                    break;

                case 36:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#ffdf3d"), Color.parseColor("#ff983d"), Color.parseColor("#FFFFFF"));
                    break;

                case 35:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#fffc3d"), Color.parseColor("#ff9b3d"), Color.parseColor("#FFFFFF"));
                    break;


                case 34:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#ffec3d"), Color.parseColor("#ffa53d"), Color.parseColor("#FFFFFF"));
                    break;


                case 33:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#ffef3d"), Color.parseColor("#ffae3d"), Color.parseColor("#FFFFFF"));
                    break;


                case 32:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#fff23d"), Color.parseColor("#fff23d"), Color.parseColor("#FFFFFF"));
                    break;

                case 31:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#fff53d"), Color.parseColor("#ffc23d"), Color.parseColor("#FFFFFF"));
                    break;

                case 30:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#fff93d"), Color.parseColor("#ffd83d"), Color.parseColor("#FFFFFF"));
                    break;

                case 29:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#fffc3d"), Color.parseColor("#ffe23d"), Color.parseColor("#FFFFFF"));
                    break;


                case 28:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#f9ff3d"), Color.parseColor("#ffec3d"), Color.parseColor("#FFFFFF"));
                    break;


                case 27:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#efff3d"), Color.parseColor("#fff53d"), Color.parseColor("#FFFFFF"));
                    break;


                case 26:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#e5ff3d"), Color.parseColor("#ffff3d"), Color.parseColor("#FFFFFF"));
                    break;


                case 25:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#dbff3d"), Color.parseColor("#f5ff3d"), Color.parseColor("#FFFFFF"));
                    break;


                case 24:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#d2ff3d"), Color.parseColor("#ecff3d"), Color.parseColor("#FFFFFF"));
                    break;


                case 23:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#beff3d"), Color.parseColor("#dfff3d"), Color.parseColor("#FFFFFF"));
                    break;
                case 22:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#aeff3d"), Color.parseColor("#d2ff3d"), Color.parseColor("#FFFFFF"));
                    break;
                case 21:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#a1ff3d"), Color.parseColor("#c5ff3d"), Color.parseColor("#FFFFFF"));
                    break;
                case 20:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#8eff3d"), Color.parseColor("#b1ff3d"), Color.parseColor("#FFFFFF"));
                    break;
                case 19:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#77ff3d"), Color.parseColor("#98ff3d"), Color.parseColor("#FFFFFF"));
                    break;
                case 18:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#3dff3d"), Color.parseColor("#5eff3d"), Color.parseColor("#FFFFFF"));
                    break;
                case 17:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#3dff7e"), Color.parseColor("#3dff4d"), Color.parseColor("#FFFFFF"));
                    break;
                case 16:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#3dffcf"), Color.parseColor("#3dff7e"), Color.parseColor("#FFFFFF"));
                    break;
                case 15:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#3dffff"), Color.parseColor("#3dffbe"), Color.parseColor("#FFFFFF"));
                    break;
                case 14:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#3daeff"), Color.parseColor("#3defff"), Color.parseColor("#FFFFFF"));
                    break;

                case 13:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#3d5eff"), Color.parseColor("#3d9eff"), Color.parseColor("#FFFFFF"));
                    break;


                case 12:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#3d3dff"), Color.parseColor("#3d7eff"), Color.parseColor("#FFFFFF"));
                    break;


                case 11:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#4d3dff"), Color.parseColor("#3d6eff"), Color.parseColor("#FFFFFF"));
                    break;

                case 10:                                                                                             //主色
                    pro_bar.setGradientColorAndBorderColor(Color.parseColor("#5e3dff"), Color.parseColor("#3d5eff"), Color.parseColor("#FFFFFF"));
                    break;


            }

        }
    }
}
